package org.dfl.plugin.editor.commands;

import org.dfl.messages.Messages;
import org.dfl.plugin.editor.model.DflDiagram;
import org.dfl.plugin.editor.model.PlaceModelElement;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.commands.Command;


/**
 * command that creates a place
 * @author Piotr Wlodarczyk
 *
 */
public class PlaceCreateCommand extends Command {

	/** The new PlaceModelElement. */
	private PlaceModelElement placeModelElement;

	/** ShapeDiagram to add to. */
	private final DflDiagram diagram;

	/** The bounds of the new Shape. */
	private Rectangle bounds;

	/**
	 * Create a command that will add a new Shape to a ShapesDiagram.
	 * 
	 * @param transitionModelElement
	 *            the new Shape that is to be added
	 * @param diagram
	 *            the ShapesDiagram that will hold the new element
	 * @param bounds
	 *            the bounds of the new shape; the size can be (-1, -1) if not
	 *            known
	 * @throws IllegalArgumentException
	 *             if any parameter is null, or the request does not provide a
	 *             new Shape instance
	 */
	public PlaceCreateCommand(PlaceModelElement newPlaceModelElement, DflDiagram diagram,
			Rectangle bounds) {
		this.placeModelElement = newPlaceModelElement;
		this.diagram = diagram;
		this.bounds = bounds;
		setLabel(Messages.PlaceCreateCommand_label);
	}

	/**
	 * Can execute if all the necessary information has been provided.
	 * 
	 * @see org.eclipse.gef.commands.Command#canExecute()
	 */
	public boolean canExecute() {
		return (diagram != null && diagram.isEditable() && bounds != null);
	}

	@Override
	public boolean canUndo() {
		return (super.canUndo() && diagram != null && diagram.isEditable());
	}
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.gef.commands.Command#execute()
	 */
	public void execute() {
		placeModelElement = new PlaceModelElement();
		placeModelElement.setLocation(bounds.getLocation());
		Dimension size = bounds.getSize();
		if (size.width > 0 && size.height > 0)
			placeModelElement.setSize(size);
		redo();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.gef.commands.Command#redo()
	 */
	public void redo() {
		diagram.addChild(placeModelElement);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.gef.commands.Command#undo()
	 */
	public void undo() {
		diagram.removeChild(placeModelElement);
	}

}